﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using Common.Utilities.Dispatcher;

namespace Workflows.Components.FileManipulation
{
    /// <summary>
    /// 
    /// </summary>
    public class FtpWorker:IWorker
    {
        private Thread _WorkerThread;
        private FtpInstruction _Instruction;
        private FtpOutput _Output;
        private RunContext _Context;
        private Guid _TicketID;
        private string _WorkflowName;
        private string _ComponentName;

        /// <summary>
        /// 
        /// </summary>
        public string ComponentName
        {
            get { return _ComponentName; }
        }

        /// <summary>
        /// 
        /// </summary>
        public string WorkflowName
        {
            get { return _WorkflowName; }
        }

        public Thread WorkerThread
        {
            get { return _WorkerThread; }
        }

        public InstructionBase Instruction
        {
            get { return _Instruction; }
        }

        public ResultBase Output
        {
            get { return _Output; }
        }

        public Type ComponentType
        {
            get { return typeof(FtpComponent); }
        }

        public RunContext Context
        {
            get { return _Context; }
            set { _Context = value; }
        }

        public void SetInstruction(Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._TicketID = ticketGuid;
            this._Instruction = (FtpInstruction) request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void SetInstruction(RunContext context, Guid ticketGuid, InstructionBase request, string workflowName, string componentName)
        {
            this._Context = context;
            this._TicketID = ticketGuid;
            this._Instruction = (FtpInstruction) request;
            this._WorkflowName = workflowName;
            this._ComponentName = componentName;
        }

        public void DoWork()
        {
            if(this.WorkerStartedEvent !=null)
            {
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = Thread.CurrentThread;
            this.TransferFile();
        }

        public void DoWorkAsync()
        {
            if (this.WorkerStartedEvent != null)
            {
                this.WorkerStartedEvent(this._TicketID, this, this.GetType(), this._Instruction);
            }
            this._WorkerThread = new Thread(new ThreadStart(this.TransferFile));
            this._WorkerThread.Start();
        }

        public void CancelWork()
        {
            if(this._WorkerThread !=null && this._WorkerThread.IsAlive)
            {
                this._WorkerThread.Abort();
                this._WorkerThread.Join();

                if(this.WorkerCancelledEvent !=null)
                {
                    this.WorkerCancelledEvent(this._TicketID, this.GetType(), this._Instruction);
                }
            }
        }

        public event WorkerStarted WorkerStartedEvent;
        public event WorkerFinished WorkerFinishedEvent;
        public event WorkerHasError WorkerErredEvent;
        public event WorkerCancelled WorkerCancelledEvent;
        public event WorkerStatusChanged WorkerStatusChangedEvent;

        #region transfer file
        private void TransferFile()
        {
            string siteName = string.Empty;
            string fileName = this._Instruction.SrcPath;
            
            if(this._Instruction.Direction==FtpDirection.Upload)
            {
                fileName = Path.GetFileName(this._Instruction.SrcPath);
            }
            else
            {
                fileName = this._Instruction.SrcPath;
                if(this._Instruction.SrcPath.IndexOf("/")>0)
                {
                    fileName = this._Instruction.SrcPath.Substring(this._Instruction.SrcPath.LastIndexOf("/") + 1);
                }
            }
            
            if(this._Instruction.Direction==FtpDirection.Download)
            {
                if(this._Instruction.SrcPath.IndexOf("/")>0)
                {
                    siteName = this._Instruction.SrcPath.Substring(0, this._Instruction.SrcPath.LastIndexOf("/"));
                }
            }
            else
            {
                if(this._Instruction.TgtFolder.IndexOf("/")>0)
                {
                    siteName = this._Instruction.TgtFolder.Substring(0, this._Instruction.TgtFolder.LastIndexOf("/"));
                }
            }
            string tgtFilePath = this._Instruction.TgtFolder;
            if (this._Instruction.Direction == FtpDirection.Download)
            {
                tgtFilePath = Path.Combine(this._Instruction.TgtFolder, fileName);
            }
            else
            {
                tgtFilePath = this._Instruction.TgtFolder + "/" + fileName;
            }
            if(this._Instruction.WindowsAuth || this._Instruction.Anonymous)
            {
                this._Instruction.UserName = string.Empty;
                this._Instruction.Password = string.Empty;
            }
            try
            {
                bool flag = false;
                if (this._Instruction.Protocol == FtpProtocol.Ftps)
                {
                    if (this._Instruction.Direction == FtpDirection.Download)
                    {
                        flag = FtpsClient.Download(this._Instruction.FtpSite, siteName, fileName, tgtFilePath,
                                                   this._Instruction.UserName, this._Instruction.Password);
                    }
                    else
                    {
                        flag = false;
                        throw new NotImplementedException("Ftps protocol is not implemented");
                    }
                }
                else
                {
                    FTPclient ftpClient = new FTPclient(this._Instruction.FtpSite, siteName, this._Instruction.UserName,
                                                        this._Instruction.Password);
                    if (this._Instruction.Direction == FtpDirection.Download)
                    {
                        flag = ftpClient.Download(fileName, Path.Combine(this._Instruction.TgtFolder, fileName), true);
                    }
                    else
                    {
                        flag = ftpClient.Upload(this._Instruction.SrcPath, fileName);
                    }
                    if (flag == false)
                    {
                        throw new Exception("Failed to " + this._Instruction.Direction + " file");
                    }
                }

                this._Output = new FtpOutput(this._Instruction.OwnerComponentID, this._TicketID, tgtFilePath);
                if(this.WorkerFinishedEvent !=null)
                {
                    this.WorkerFinishedEvent(this._TicketID, this.GetType(), this._Instruction, this._Output);
                }
            }
            catch (Exception ex)
            {
                if (this.WorkerErredEvent != null)
                {
                    this.WorkerErredEvent(this._TicketID, this.GetType(), this._Instruction, ex.ToString(),true);
                }
            }
        }
        #endregion
    }
}
